#include "EventList.h"

SK

EventList::EventList (u32 numEvents, bool initialState)
: numEvents(numEvents)
{
    han = new HANDLE [numEvents];
    for (u32 i=0; i<numEvents;i++)
        han [i] = CreateEvent (NULL, TRUE, (BOOL)initialState, NULL);
}

EventList::~EventList ()
{
    if (han)
    {
        for (u32 i=0; i<numEvents;i++)
            CloseHandle (han [i]);

        delete han;
    }
}

Event *EventList::getEvent (u32 index)
{
    return new Event (han [index]);
}

void EventList::signalAll (void)
{
    for (u32 i=0; i<this->numEvents; i++)
        SetEvent (han [i]);
}

void EventList::resetAll (void)
{
    for (u32 i=0; i<this->numEvents; i++)
        ResetEvent (this->han[i]);
}

void EventList::signal (u32 index)
{
    SetEvent (this->han[index]);
}

void EventList::reset (u32 index)
{
    ResetEvent (this->han[index]);
}

bool EventList::waitFor (u32 index)
{
    DWORD ret = WaitForSingleObject (han [index], INFINITE);
    if (ret >= WAIT_OBJECT_0 && ret <= (WAIT_OBJECT_0 + this->numEvents - 1))
        return ret - WAIT_OBJECT_0;
    
    return -1;
}

bool EventList::waitFor (u32 index, u32 timeout)
{
    DWORD ret = WaitForSingleObject (han [index], (DWORD)timeout);
    return ret == WAIT_OBJECT_0;
}

bool EventList::waitForAll (void)
{
    DWORD ret = WaitForMultipleObjects ((DWORD)numEvents, this->han, TRUE, INFINITE);
    return ret == WAIT_OBJECT_0;
}

bool EventList::waitForAll (u32 timeout)
{
    DWORD ret = WaitForMultipleObjects ((DWORD)numEvents, this->han, TRUE, (DWORD)timeout);
    return ret == WAIT_OBJECT_0;
}

int EventList::waitForAny (void)
{
    DWORD ret = WaitForMultipleObjects ((DWORD)numEvents, this->han, FALSE, INFINITE);
    if (ret >= WAIT_OBJECT_0 && ret <= (WAIT_OBJECT_0 + this->numEvents - 1))
        return ret - WAIT_OBJECT_0;
    
    return -1;
}

int EventList::waitForAny (u32 timeout)
{
    DWORD ret = WaitForMultipleObjects ((DWORD)numEvents, this->han, FALSE, (DWORD)timeout);
    if (ret >= WAIT_OBJECT_0 && ret <= (WAIT_OBJECT_0 + this->numEvents - 1))
        return ret - WAIT_OBJECT_0;
    
    return -1;
}

EK